import React, { useState, useEffect } from 'react';
import { Layout, Menu, Drawer, Button, Space, Dropdown } from 'antd';
import { 
  MenuOutlined, 
  DashboardOutlined, 
  CloudOutlined, 
  BarChartOutlined, 
  SettingOutlined, 
  EnvironmentOutlined,
  BellOutlined,
  ThunderboltOutlined,
  AppstoreAddOutlined,
  UserOutlined,
  LogoutOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import type { MenuProps } from 'antd';

const { Header, Sider, Content } = Layout;

interface ResponsiveLayoutProps {
  children: React.ReactNode;
  selectedKey: string;
  onMenuSelect: (key: string) => void;
  onLogout: () => void;
  username?: string;
  onExport?: () => void;
}

interface ScreenSize {
  width: number;
  height: number;
  isMobile: boolean;
  isTablet: boolean;
  isDesktop: boolean;
}

const useScreenSize = (): ScreenSize => {
  const [screenSize, setScreenSize] = useState<ScreenSize>({
    width: window.innerWidth,
    height: window.innerHeight,
    isMobile: window.innerWidth < 768,
    isTablet: window.innerWidth >= 768 && window.innerWidth < 1024,
    isDesktop: window.innerWidth >= 1024
  });

  useEffect(() => {
    const handleResize = () => {
      const width = window.innerWidth;
      const height = window.innerHeight;
      setScreenSize({
        width,
        height,
        isMobile: width < 768,
        isTablet: width >= 768 && width < 1024,
        isDesktop: width >= 1024
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return screenSize;
};

const ResponsiveLayout: React.FC<ResponsiveLayoutProps> = ({
  children,
  selectedKey,
  onMenuSelect,
  onLogout,
  username,
  onExport
}) => {
  const [mobileMenuVisible, setMobileMenuVisible] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const screenSize = useScreenSize();

  // 自动控制侧边栏折叠状态
  useEffect(() => {
    if (screenSize.isMobile) {
      setCollapsed(true);
    } else if (screenSize.isTablet) {
      setCollapsed(true);
    } else {
      setCollapsed(false);
    }
  }, [screenSize.isMobile, screenSize.isTablet]);

  const menuItems: MenuProps['items'] = [
    {
      key: '1',
      icon: <DashboardOutlined />,
      label: '仪表板'
    },
    {
      key: '2',
      icon: <CloudOutlined />,
      label: '天气数据'
    },
    {
      key: '3',
      icon: <BarChartOutlined />,
      label: '数据统计'
    },
    {
      key: '4',
      icon: <SettingOutlined />,
      label: '系统设置'
    },
    {
      key: '5',
      icon: <EnvironmentOutlined />,
      label: '城市管理'
    },
    {
      key: '6',
      icon: <BellOutlined />,
      label: '告警系统'
    },
    {
      key: '7',
      icon: <AppstoreAddOutlined />,
      label: '批量操作'
    },
    {
      key: '8',
      icon: <ThunderboltOutlined />,
      label: '性能监控'
    }
  ];

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'export',
      icon: <DownloadOutlined />,
      label: '数据导出',
      onClick: onExport
    },
    {
      type: 'divider'
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: onLogout
    }
  ];

  const handleMenuClick = ({ key }: { key: string }) => {
    onMenuSelect(key);
    if (screenSize.isMobile) {
      setMobileMenuVisible(false);
    }
  };

  const renderSidebar = () => (
    <Menu
      theme="dark"
      mode="inline"
      selectedKeys={[selectedKey]}
      onClick={handleMenuClick}
      items={menuItems}
      inlineCollapsed={collapsed && !screenSize.isMobile}
      style={{ height: '100%', borderRight: 0 }}
    />
  );

  if (screenSize.isMobile) {
    return (
      <Layout style={{ minHeight: '100vh' }}>
        {/* 移动端顶部导航栏 */}
        <Header style={{ 
          position: 'fixed', 
          zIndex: 1001, 
          width: '100%', 
          padding: '0 16px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          background: '#001529'
        }}>
          <Space>
            <Button
              type="text"
              icon={<MenuOutlined />}
              onClick={() => setMobileMenuVisible(true)}
              style={{ color: 'white' }}
            />
            <div style={{ color: 'white', fontSize: '16px', fontWeight: 'bold' }}>
              天气系统
            </div>
          </Space>
          
          <Dropdown
            menu={{ items: userMenuItems }}
            placement="bottomRight"
            arrow
          >
            <Button
              type="text"
              icon={<UserOutlined />}
              style={{ color: 'white' }}
            >
              {username || '用户'}
            </Button>
          </Dropdown>
        </Header>

        {/* 移动端抽屉菜单 */}
        <Drawer
          title="导航菜单"
          placement="left"
          closable={true}
          onClose={() => setMobileMenuVisible(false)}
          open={mobileMenuVisible}
          bodyStyle={{ padding: 0 }}
        >
          {renderSidebar()}
        </Drawer>

        {/* 主内容区域 */}
        <Content style={{ 
          marginTop: 64, // Header高度
          padding: '16px',
          minHeight: 'calc(100vh - 64px)'
        }}>
          {children}
        </Content>
      </Layout>
    );
  }

  // 平板和桌面端布局
  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* 侧边栏 */}
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={setCollapsed}
        breakpoint="lg"
        collapsedWidth={screenSize.isTablet ? 0 : 80}
        style={{
          position: screenSize.isDesktop ? 'relative' : 'fixed',
          height: '100vh',
          left: 0,
          top: 0,
          bottom: 0,
          zIndex: 1000
        }}
      >
        <div style={{ 
          height: 32, 
          margin: 16, 
          background: 'rgba(255, 255, 255, 0.3)',
          borderRadius: 4
        }} />
        {renderSidebar()}
      </Sider>

      <Layout style={{ 
        marginLeft: screenSize.isTablet && !collapsed ? 200 : screenSize.isDesktop ? (collapsed ? 80 : 200) : 0 
      }}>
        {/* 顶部导航栏 */}
        <Header style={{ 
          padding: '0 24px', 
          background: '#fff',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          boxShadow: '0 1px 4px rgba(0,21,41,.08)'
        }}>
          <h1 style={{ 
            margin: 0, 
            fontSize: screenSize.isTablet ? '18px' : '24px',
            color: '#001529',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
          }}>
            天气数据采集与统计系统
          </h1>
          
          <Space>
            {onExport && (
              <Button
                type="primary"
                ghost
                icon={<DownloadOutlined />}
                onClick={onExport}
                size={screenSize.isTablet ? 'small' : 'middle'}
              >
                {screenSize.isTablet ? '' : '导出'}
              </Button>
            )}
            
            <Dropdown
              menu={{ items: userMenuItems }}
              placement="bottomRight"
              arrow
            >
              <Button type="text" icon={<UserOutlined />}>
                {username || '用户'}
              </Button>
            </Dropdown>
          </Space>
        </Header>

        {/* 主内容区域 */}
        <Content style={{
          margin: '24px 16px',
          padding: 24,
          background: '#fff',
          minHeight: 'calc(100vh - 112px)',
          borderRadius: 6
        }}>
          {children}
        </Content>
      </Layout>
    </Layout>
  );
};

export default ResponsiveLayout;